import React, { Component } from 'react'
import './index.css'
import axios from 'axios'
export default class Home extends Component {
  state = {
    val: '', //搜索框的值
  }
  // 点击新增按钮跳转页面
  toaAdd = () => {
    this.props.history.push('/add')
  }
  //跳转编辑页面
  toEdit = (item) => {
    this.props.history.push({ pathname: '/edit', state: { id: item.id, item } })
  }
  //删除
  del = (item) => {
    axios.get('/del/city', { params: { id: item.id } }).then(() => {
      window.location.reload()
    })
  }
  //封装查询的函数
  cityRender = () => {
    const { cityList } = this.props
    let newList = [...cityList] //查询后的新列表，替换旧的列表
    if (this.state.val !== '') {
      newList = newList.filter((item) => item.name.indexOf(this.state.val) > -1)
    }
    return (
      <div>
        {newList.length > 0 &&
          newList.map((item, index) => {
            return (
              <div className="list_item" key={index}>
                <div>
                  <p>{item.name}</p>
                  <p>{item.phone}</p>
                  <p>{item.region}</p>
                  <p>{item.address}</p>
                </div>
                <button onClick={() => this.toEdit(item)}>编辑</button>
                <button onClick={() => this.del(item)}>删除</button>
              </div>
            )
          })}
      </div>
    )
  }
  render() {
    const { cityList } = this.props
    console.log(cityList, 'list')
    return (
      <div className="app">
        <header className="header">
          <input
            type="text"
            placeholder="请输入姓名进行查询"
            onChange={(e) => this.setState({ val: e.target.value })}
          />
        </header>
        <main className="main">
          {this.cityRender()}
          {/* {cityList.length > 0 &&
            cityList.map((item, index) => {
              return (
                <div className="list_item" key={index}>
                  <div>
                    <p>{item.name}</p>
                    <p>{item.phone}</p>
                    <p>{item.region}</p>
                    <p>{item.address}</p>
                  </div>
                  <button onClick={() => this.toEdit(item)}>编辑</button>
                  <button onClick={() => this.del(item)}>删除</button>
                </div>
              )
            })} */}
        </main>
        <footer className="footer">
          <button onClick={() => this.toaAdd()}>新增地址</button>
        </footer>
      </div>
    )
  }
}
